package com.company.management.config;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.company.management.domain.reward.ScoreLevel;
import com.company.management.domain.reward.ScoreLog;
import com.company.management.mapper.TaskMapper;
import com.company.management.mapper.UserMapper;
import com.company.management.mapper.reward.ScoreLevelMapper;
import com.company.management.mapper.reward.ScoreLogMapper;
import com.company.management.modal.entity.Task;
import com.company.management.modal.entity.User;
import com.company.management.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;

@Slf4j
@EnableScheduling
@Component
public class TaskScoreSchedulerConfig{
    @Resource
    private UserMapper userMapper;
    @Resource
    private TaskMapper taskMapper;
    @Resource
    private ScoreLevelMapper scoreLevelMapper;
    @Resource
    private ScoreLogMapper scoreLogMapper;

    @Scheduled(cron = "0 0/30 * * * ?") // 每半小时执行一次
    public void dealTask() {
        long start = System.currentTimeMillis();
        log.info("{}...", LocalDateTime.now());
        List<ScoreLog> scoreLogList = new ArrayList<>();
        QueryWrapper<Task> condition = new QueryWrapper<>();
        Task taskvo = new Task();
        taskvo.setValidFlag(1);
        condition.setEntity(taskvo);
        condition.isNotNull("DeadTime");//截止日期不等于null
        condition.isNotNull("FromId");
        //查询未完成和已完成的所有任务
        List<Task> taskList = taskMapper.selectList(condition);//查询所有未完成的任务信息
        taskList.stream().forEach(task -> {
            long backUpId = task.getBackUpId();
            QueryWrapper<ScoreLog> queryWrapper = new QueryWrapper<>();
            ScoreLog scoreLog001 = new ScoreLog();
            scoreLog001.setFid(backUpId);
            queryWrapper.setEntity(scoreLog001);
            List<ScoreLog> scoreList  = scoreLogMapper.selectList(queryWrapper);
            if(com.baomidou.mybatisplus.core.toolkit.CollectionUtils.isEmpty(scoreList)){
                dealTask(task);
            }
        });
        long end = System.currentTimeMillis();
        long costTime = end - start;
        log.info("{}...", costTime);
    }
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void dealTask(Task task){
        ScoreLog scoreLog = new ScoreLog();
        scoreLog.setCreateDateTime(new Date());
        scoreLog.setUserId(task.getCreateID());
        User user = userMapper.selectById(task.getCreateID());
        int beforeScore = user.getScore();
        scoreLog.setBeforeScore(beforeScore);
        scoreLog.setFid(task.getBackUpId());//与taskId映射唯一
        scoreLog.setFName("任务");
        QueryWrapper<ScoreLevel> con = new QueryWrapper<>();
        ScoreLevel scoreLevel = new ScoreLevel();
        scoreLevel.setModule(2);//2-任务模块
        boolean flag = true;
        if (0 == task.getFinishStatus()) {
            scoreLevel.setFlag(1);//未完成
            flag = false;
        } else {
            scoreLevel.setFlag(0);//已完成
            flag = true;
        }
        con.setEntity(scoreLevel);
        ScoreLevel scoreLevelVo = scoreLevelMapper.selectOne(con);
        if (Objects.nonNull(scoreLevelVo)) {
            scoreLog.setSid(scoreLevelVo.getSid());//扣分/加分机制表
            scoreLog.setUpdateScore(String.valueOf(scoreLevelVo.getScore()));
            int score = scoreLevelVo.getScore();
            if (flag) {
                scoreLog.setUpdateScore("+"+String.valueOf(scoreLevelVo.getScore()));
                scoreLog.setAfterScore(beforeScore + score);//已完成+扣分
            } else {
                scoreLog.setAfterScore(beforeScore - score);//未完成-扣分
                scoreLog.setUpdateScore("-"+String.valueOf(scoreLevelVo.getScore()));

            }
        }
        scoreLogMapper.insert(scoreLog);
        Map<Integer, Integer> userScores = new HashMap<>();
        int userId = scoreLog.getUserId();
        int before = scoreLog.getBeforeScore();
        int change = Integer.parseInt(scoreLog.getUpdateScore());
        if (userScores.containsKey(userId)) {
            int currentScore = userScores.get(userId);
            userScores.put(userId, currentScore + change);
        } else {
            userScores.put(userId, before + change);
        }
        User user0 = new User();
        user0.setScore(userScores.get(userId));
        user0.setUserId(userId);
        user0.setUpdateTime(LocalDateTime.now());
        userMapper.updateById(user0);
    }
}
